#include<bits/stdc++.h>
#define int long long 
using namespace std;
char buf[(1<<21)+5],*p1,*p2;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
int read(){
	int f=0,x=0;
	char ch=getchar();
	while(!isdigit(ch)){f|=(ch=='-');ch=getchar();}
	while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
	return f?-x:x;
}


int n,ans=-1e18,a[405];
vector<int> G[405];
int dep[405],siz[405],top[405],son[405],fa[405],dfn[405],tot;
void dfs1(int u,int f){
	dep[u]=dep[f]+1;
	fa[u]=f;
	siz[u]=1;
	int maxson=-1;
	for(auto v:G[u])
		if(v!=f){
			dfs1(v,u);
			siz[u]+=siz[v];
			if(siz[v]>maxson){
				son[u]=v;
				maxson=siz[v];
			}
		}			
}
void dfs2(int u,int p){
	top[u]=p;
	dfn[u]=++tot;
	if(son[u])
		dfs2(son[u],p);
	for(auto v:G[u]){
		if(v!=fa[u]&&v!=son[u])
			dfs2(v,v);
	}
}
int LCA(int x,int y){
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]])
			swap(x,y);
		x=fa[top[x]];
	}
	return dep[x]<dep[y]?x:y;
}
/*int SIZE(int R,int x){
	int ans=0;
	for(auto v:G[x]){
		if(x==R||!(dfn[v]<=dfn[R]&&dfn[R]<siz[v]+dfn[v])){
			ans+=siz[v];
			if(v==fa[x])
				ans-=siz[x];
		}
			
	}
	
	return ans;
  }*/
int t[15];
int check(){
	bool vis[15];
	int xans=0;
	int f[15];
	for(int i=1;i<=n;i++)
		f[i]=a[i];
	memset(vis,0,sizeof vis);
	for(int i=1;i<=n;i++){
		xans+=f[t[i]];
		for(auto v:G[t[i]])
			f[v]+=f[t[i]];
	}
	return xans;
}
signed main(){
	freopen("light.in","r",stdin);
	freopen("light.out","w",stdout);
	n=read();
	for(int i=1;i<=n;i++)
		a[i]=read();
	for(int i=1;i<n;i++){
		int x,y;
		x=read(),y=read();
		G[x].emplace_back(y);
		G[y].emplace_back(x);
	}
	if(n<=10){
		dfs1(1,1);
		dfs2(1,1);
		
		for(int i=1;i<=n;i++)
		t[i]=i;
		do{
			
			ans=max(check(),ans);
		}while(next_permutation(t+1,t+1+n));
		cout<<ans<<endl;
		return 0;
	}
	
	for(int i=1;i<=n;i++){
		int xans=0;
		tot=0;
		memset(dep,0,sizeof dep);
		memset(top,0,sizeof top);
		memset(siz,0,sizeof siz);
		memset(son,0,sizeof son);
		dfs1(i,i);
		dfs2(i,i);
		
		for(int j=1;j<=n;j++){
			//int lca=LCA(i,j);
			
			int d=0;
			//d+=abs(dep[lca]-dep[i]);
			d+=abs(dep[j]);
			
			xans+=a[j]*(d);
			
		}
		//cout<<xans<<endl;
		ans=max(ans,xans);
		xans=0;
		for(int j=1;j<=n;j++){
			xans+=a[j]*siz[j];
		}
		//cout<<xans<<endl;
		ans=max(xans,ans);
	}
	cout<<ans<<endl;
	return 0;
}
